//
//  WitnessSignForNewStcFormVC.swift
//  ezyform
//
//  Created by Moennig Q on 6/5/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit

class WitnessSignForNewStcFormVC: BaseViewController {
    weak var model: PVDDetailModel!
    let customView = WitnessSignForNewStcFormView(customBackToPreFlag: true)
    //
    override func viewDidLoad() {
        super.viewDidLoad()
        self.model = JobDetailModelHelper.shared.jobDetailModel
        initUI()
    }
    func initUI(){
        //title
        self.view = self.customView
        self.customView.setTitleInfo(APPConfig.loginInfo.currentSignatureType.rawValue + " Signature")
        self.customView.backToPreBtn.addTarget(self, action: #selector(backToPreVieController), for: UIControl.Event.touchUpInside)
        self.customView.saveBtn.addTarget(self, action: #selector(saveBtnClick), for: UIControl.Event.touchUpInside)
        self.customView.setData()
    }
    @objc func backToPreVieController() {
        Tool().showAlertViewWithTwoBtns(message: R.string.localizable.pvdDetailSignaturesSignatureBackfromsignTip(),  yesClosure: {[weak self] in
            self?.navigationController?.popViewController(animated: false)
        })
    }
    @objc func saveBtnClick(){
        self.customView.endEditing(true)
        //检查是否已签名
        if !self.customView.signView.signaturedFlag {
            Tool().showAlertViewWithOneBtn(message: R.string.localizable.pleaseSignBeforeSaving())
            return
        }
        
        //witness
        self.customView.signedTextfield.textField.resignFirstResponder()
        let signedName = self.customView.signedTextfield.textField.text ?? ""
        if signedName == "" {
            self.customView.signedTextfield.showInvalidMsg( R.string.localizable.pleaseTypeWitnessSName())
            return
        }else{
            self.customView.signedTextfield.hideInvalidMsg()
        }
        
        self.saveSignature()

    }
    func saveSignature(){
        let image = self.customView.signView.getSignature()
        
        if let imageData = image.pngData() {
            self.customView.saveBtn.disableBtn()//此处是防止多次点击saveBtn，重复提交签名导致错误提示（NEWGD-914）
            let witnessSignedName = self.customView.signedTextfield.textField.text ?? ""
            let witnessSibnedImageData = NSData(data: imageData)
            let witnessSignedAt = DateUtil().getCurrentDatetime()
            APPConfig.loginInfo.signatureInfoModel.pvd_id = JobDetailModelHelper.shared.jobDetailModel.id
            //签名图片
            switch APPConfig.loginInfo.currentSignatureType {
            case .Installer:
                //installer签名协议中引用的Job 信息数据也传递到后台
//                APPConfig.loginInfo.signatureInfoModel.statement_input_param_all = InstallationDetailVCHelper.shared.getAllRequiredJsonForSign(self.model, signTypes: [.Installer])
                APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_signature = witnessSibnedImageData
                APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_date = witnessSignedAt
                APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_name = witnessSignedName
            case .Designer:
                //designer签名协议中引用的Job 信息数据也传递到后台
//                APPConfig.loginInfo.signatureInfoModel.statement_input_param_all = InstallationDetailVCHelper.shared.getAllRequiredJsonForSign(self.model, signTypes: [.Designer])
                APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_signature = witnessSibnedImageData
                APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_date = witnessSignedAt
                APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_name = witnessSignedName
            case .Owner:
                //owner签名协议中引用的Job 信息数据也传递到后台
//                APPConfig.loginInfo.signatureInfoModel.statement_input_param_all = InstallationDetailVCHelper.shared.getAllRequiredJsonForSign(self.model, signTypes: [.Owner])
                APPConfig.loginInfo.signatureInfoModel.witness_sign_imagedata = witnessSibnedImageData
                APPConfig.loginInfo.signatureInfoModel.witness_signed_at = witnessSignedAt
                APPConfig.loginInfo.signatureInfoModel.witness_signed_name = witnessSignedName
                //
//                if let isAussolarco = self.model!.is_aus_solar_co,isAussolarco {
//                    APPConfig.loginInfo.signatureInfoModel.owner_aussolarco_satisfactory_version = "1"
//                    APPConfig.loginInfo.signatureInfoModel.owner_satisfaction_completion_version = "1"
//                }
            case .InstallerAndDesiger:
                //installer，designer签名协议中引用的Job 信息数据也传递到后台
//                APPConfig.loginInfo.signatureInfoModel.statement_input_param_all = InstallationDetailVCHelper.shared.getAllRequiredJsonForSign(self.model, signTypes: [.Installer,.Designer])
                //installer
                APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_signature = witnessSibnedImageData
                APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_date = witnessSignedAt
                APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_name = witnessSignedName
                //Designer
                APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_signature = witnessSibnedImageData
                APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_date = witnessSignedAt
                APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_name = witnessSignedName
            default:
                break
            }
            
            //上传签名
            InstallationSignatureService().setDataInfo(self).requestUploadSignature() { [weak self] in
                guard let strongSelf = self else { return  }
                InstallationSignatureService().setDataInfo(strongSelf).dealLocalSignatureByWitnessSave()//删除本地数据
                InstallationSignatureService().setDataInfo(strongSelf).backToDetailVC()
            } faildClosure: { (code, errMsg) in
                Tool().showErrorInfo(code,errMsg)
            }
        }else{
            Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.signatures.signature.save.faild", comment: ""))
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }

}
